package net.ck.hzq;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.net.URL;
import java.util.HashMap;

import Utils.ResourcesManager;
import base.BaseActivity;
import base.BaseBiz;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import ui.activity.home.biz.CreditCardsBiz;
import ui.model.CreditCardsBean;
import ui.model.ShareParamBean;
import util.LogUtils;
import util.StringUtils;
import util.ToastUtils;

public class WebShareActivity extends BaseActivity implements View.OnClickListener {

    private WebView webview;
    private ImageView back;
    private ImageView share;
    private TextView title;
    CreditCardsBean bean;
    private String shareData = "";
    CreditCardsBiz biz;

    @Override
    public int getLayoutId() {
        return R.layout.activity_share_webview;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        setListener();
        setData();
    }

    private void setData() {
        bean = (CreditCardsBean) getIntent().getSerializableExtra("data");
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
//        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");
        title.setText(bean.getName());
        webview.loadUrl(bean.getLink());
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:")) {
                    view.loadUrl(url);
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    private void setListener() {
        back.setOnClickListener(this);
        share.setOnClickListener(this);
    }

    private void initView() {
        webview = findViewById(R.id.webview);
        back = findViewById(R.id.iv_back);
        share = findViewById(R.id.iv_share);
        title = findViewById(R.id.title_info);
        biz = new CreditCardsBiz();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                getShareData();
                break;
        }
    }

    private void getShareData() {
        share.setEnabled(false);
        ShareParamBean shareParamBean = new ShareParamBean();
        shareParamBean.setFlat("");
        shareParamBean.setShareTo("");
        shareParamBean.setType("2");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(shareParamBean));
        biz.getShareList(requestBody, new BaseBiz.Callback<String>() {
            @Override
            public void onSuccess(String info) {
                shareData = info;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            onOneKeyShare();
                        } catch (Exception e) {
                            ToastUtils.shortToast(e.getMessage() + "");
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            @Override
            public void onFailure(String info) {

                share.setEnabled(true);
            }
        });
    }

    /**
     * 一键分享
     */
    private void onOneKeyShare() {
        //TODO
        String url = bean.getLink() + "?shareNo=" + shareData + "&customId=" + TobuyApplication.getCustomId() + "&pId=" + bean.getId() + "&isShow=1";
        cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        oks.setAddress(url);
        ResourcesManager manager = ResourcesManager.getInstace(WebShareActivity.this);
        oks.setTitle(bean.getName());//标题
        oks.setText(bean.getComment());//内容
        oks.setUrl(url);//链接
        oks.setTitleUrl(url);
        Bitmap thumbBmp = null;
        if (StringUtils.isEmpty(bean.getSmallImg())) {
            thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_new);
        } else {
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(new URL(bean.getSmallImg()).openStream());
                thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 150, true);
//                msg.thumbData = Util.bmpToByteArray(createBitmapThumbnail(thumbBmp, true), true);
            } catch (Exception e) {
                LogUtils.d("-----------");
                thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_new);
            }
        }
        oks.setImageData(thumbBmp);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                Message message = new Message();
                message.obj = text;
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                Message message = new Message();
                message.obj = text;
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
                Message message = new Message();
                message.obj = text;
            }
        });
        oks.show(WebShareActivity.this);
        share.setEnabled(true);
    }

}
